﻿using System;
using System.Configuration;
using System.Linq;
using System.Web.UI.WebControls;
using BusinessLogic.Model;
using BusinessLogic;

namespace Admin
{
    public partial class IPInfo : System.Web.UI.Page
    {
        private BlogNETDataContext dc;
        public BlogNETDataContext DataContext
        {
            get { return dc; }
        }

        #region PageEvents

        protected void Page_PreInit(object sender, EventArgs e)
        {
            dc = new BlogNETDataContext(ConfigurationManager.ConnectionStrings["BlogNETDB"].ConnectionString);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            string ip = Request.QueryString[QueryStringConstants.IP];
            lblIPAddress.Text = ip;

            gvUsernames.DataSource = from comment in dc.Comments
                                     where comment.IPAddress == ip
                                     group comment.AuthorUsername by comment.AuthorUsername into result
                                     select new { Username = result.Key };
            gvUsernames.DataBind();

            gvComments.DataSource = ldsInfo;
            gvComments.DataBind();
        }

        protected void Page_Unload(object sender, EventArgs e)
        {
            if (dc != null)
            {
                dc.Dispose();
            }
        }

        #endregion

        protected void ldsInfo_Selecting(object sender, LinqDataSourceSelectEventArgs e)
        {
            var info = from comment in dc.Comments
                       where comment.IPAddress == Request.QueryString[QueryStringConstants.IP]
                       join ni in dc.NewsItems on comment.NewsItemID equals ni.NewsItemID into results
                       from result in results
                       select new
                       {
                           Username = comment.AuthorUsername,
                           Article = result.Title,
                           NewsItemID = result.NewsItemID,
                           Time = comment.PostDate,
                           Comment = comment.Text.Substring(0, 50)
                       };

            e.Result = info;
        }

        protected void gvComments_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvComments.PageIndex = e.NewPageIndex;
            gvComments.DataBind();
        }
    }
}